package com.jiandaoshou.fragments;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.listener.OnTopRefreshTime;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.interfaces.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.XLabels;
import com.jiandaoshou.JinRiDingDetailAct;
import com.jiandaoshou.MonthDingDanAct;
import com.jiandaoshou.R;
import com.jiandaoshou.adapter.ExPanAdapter;
import com.jiandaoshou.base.BaseFragment;
import com.jiandaoshou.entry.DingDanDetailEntry;
import com.jiandaoshou.entry.MonthOrderInfo;
import com.jiandaoshou.entry.OrderMonthCount;
import com.jiandaoshou.http.APIDefine;
import com.jiandaoshou.http.Http;
import com.jiandaoshou.utils.JsonUtil;
import com.jiandaoshou.utils.LogUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import rx.observers.TestObserver;

public class DingDanFragment extends BaseFragment {
    private BarChart chart;
    private BarData data;
    private BarDataSet dataSet;
    private ExpandableListView mListView;
    private XRefreshView xRefreshView;
    private ExPanAdapter adapter;
    private List<String> parents = new ArrayList<String>();
    private Map<String, List<DingDanDetailEntry>> childs = new HashMap<String, List<DingDanDetailEntry>>();
    private String shopID;
    private int year, page = 1;
    private List<OrderMonthCount> datas;
    private List<MonthOrderInfo> infos = new ArrayList<>();
    public  long lastRefreshTime;
    //下拉记载true
    private boolean flag=true;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    /**图表具体设置*/
                    ArrayList<BarEntry> entries = new ArrayList<>();//显示条目
                    ArrayList<String> xVals = new ArrayList<String>();//横坐标标签
                    datas = (List<OrderMonthCount>) msg.obj;
                    OrderMonthCount order;
                    for (int i = 0; i < datas.size(); i++) {
                        order = datas.get(i);
                        float profit = Float.valueOf(order.getNum());
                        entries.add(new BarEntry(profit, i));
                        xVals.add((i+1) + "月");
                    }
                    dataSet = new BarDataSet(entries, "");
                    dataSet.setColors(new int[]{Color.rgb(101, 203, 196)});
                    dataSet.setBarShadowColor(Color.parseColor("#ffffff"));
                    data = new BarData(xVals, dataSet);
                    chart.setData(data);
                    chart.setDrawGridBackground(false);
                    XLabels xLabels = chart.getXLabels();
                    xLabels.setPosition(XLabels.XLabelPosition.BOTTOM);
                    xLabels.setCenterXLabelText(true);
                    xLabels.setSpaceBetweenLabels(0);
                    chart.setDrawLegend(false);
                    chart.setDescription("");
                    //设置Y方向上动画animateY(int time);
                    chart.animateY(3000);
                    break;
                //显示前三个月的数据
                case 1:
                    infos = (List<MonthOrderInfo>) msg.obj;
                    SortData(infos);
                    for (int i = 0; i < infos.size(); i++) {
                        parents.add(infos.get(i).getMonth());
                        childs.put(infos.get(i).getMonth(), infos.get(i).getDatas());
                    }
                    adapter = new ExPanAdapter(getActivity(), parents, childs);
                    mListView.setAdapter(adapter);
                    mListView.setGroupIndicator(null);
                    for (int i = 0; i < parents.size(); i++) {
                        mListView.expandGroup(i);
                    }
                    if(infos.size()<10){
                        xRefreshView.setLoadComplete(true);
                        xRefreshView.stopLoadMore();
                    }
                    if(true){
                        xRefreshView.stopLoadMore();
                    }else{
                        xRefreshView.stopRefresh();
                    }
                    break;
            }
        }
    };

    @Override
    protected void lazyLoad() {
        datas = new ArrayList<OrderMonthCount>();
        shopID = getArguments().getString("shopId", "");
        //获取按照月份获取订单量
        HashMap<String, String> map = new HashMap<>();
        map.put("strShopID", shopID);
        Calendar cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);//获取年份
        map.put("strYear", year + "");
        Http.post(APIDefine.TF_Interface_GetMonthToTal, map, new Http.HttpCallBack() {
            @Override
            public void onHttpSuccess(String response) throws Exception {
                JSONObject object = new JSONObject(response);
                JSONArray array = object.getJSONArray("List");
                OrderMonthCount order;
                for (int i = 0; i < array.length(); i++) {
                    order = JsonUtil.parser.fromJson(array.get(i).toString(), OrderMonthCount.class);
                    datas.add(order);
                }
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = datas;
                msg.sendToTarget();
            }
        });

    }

    @Override
    protected int getContentView() {
        return R.layout.activity_ding_dan;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        chart = $(R.id.barchart);
        mListView = $(R.id.listview);
        xRefreshView=$(R.id.exlist_refresh);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setAutoLoadMore(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setAutoLoadMore(true);
        xRefreshView.setHideFooterWhenComplete(false);
        lastRefreshTime=System.currentTimeMillis();
        xRefreshView.restoreLastRefreshTime(lastRefreshTime);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener(){
            @Override
            public void onRefresh() {
                 super.onRefresh();
                 flag=false;
                 infos.clear();
                 GetExpendData(1);
                 xRefreshView.stopRefresh();
            }
            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                flag=true;
                page++;
                GetExpendData(page);
                xRefreshView.stopLoadMore();
            }
        });
        //设置订单详情
        initExPanList();
        chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry entry, int i) {
                int month=entry.getXIndex()+1;
                Intent intent=new Intent(getActivity(),MonthDingDanAct.class);
                intent.putExtra("type","chart");
                intent.putExtra("shopID",shopID);
                intent.putExtra("month",month+"");
                startActivity(intent);
            }
            @Override
            public void onNothingSelected() {

            }
        });
    }


    private void initExPanList() {
        GetExpendData(page);
        xRefreshView.setOnTopRefreshTime(new OnTopRefreshTime() {
            @Override
            public boolean isTop() {
                return true;
            }
        });
        mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                Intent intent=new Intent(getActivity(), MonthDingDanAct.class);
                intent.putExtra("type","list");
                intent.putExtra("shopID",shopID);
                intent.putExtra("month",parents.get(i));
                startActivity(intent);
                return true;
            }
        });
        mListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                Intent intent= new Intent(getActivity(), JinRiDingDetailAct.class);
                intent.putExtra("OrderID",infos.get(i).getDatas().get(i1).getStrOrderID());
                intent.putExtra("payMode",infos.get(i).getDatas().get(i1).getStrPaymentMode());
                intent.putExtra("aount",infos.get(i).getDatas().get(i1).getnTradingAmount());
                intent.putExtra("time",infos.get(i).getDatas().get(i1).getDtTransactionTime());
                startActivity(intent);
                return true;
            }
        });
    }

    //获取订单数据
    private void GetExpendData(int page) {
        //请求每月前10条数据
        Calendar cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);//获取年份
        shopID = getArguments().getString("shopId", "");
        parents = new ArrayList<String>();
        HashMap<String, String> map = new HashMap<>();
        map.put("strShopID", shopID);
        map.put("strYear", year + "");
        map.put("page", page + "");
        map.put("rows", 10 + "");
        Http.post(APIDefine.TF_Interface_GetTop10EveryMonth, map, new Http.HttpCallBack() {
            @Override
            public void onHttpSuccess(String response) throws Exception {
                JSONObject object = new JSONObject(response);
                JSONArray array = object.getJSONArray("monthOrders");
                List<MonthOrderInfo> infos = new ArrayList<MonthOrderInfo>();
                JSONObject json;
                MonthOrderInfo info;
                String Month;
                DingDanDetailEntry entry;
                JSONArray array1;
                for (int i = 0; i < array.length(); i++) {
                    json = (JSONObject) array.get(i);
                    Month = json.getString("month");
                    info = new MonthOrderInfo();
                    info.setMonth(Month);
                    array1 = json.getJSONArray("orderList");
                    List<DingDanDetailEntry> entryList = new ArrayList<DingDanDetailEntry>();
                    for (int j = 0; j < array1.length(); j++) {
                        entry = JsonUtil.parser.fromJson(array1.get(j).toString(), DingDanDetailEntry.class);
                        entryList.add(entry);
                    }
                    info.setDatas(entryList);
                    infos.add(info);
                }
                Message msg = handler.obtainMessage();
                msg.obj = infos;
                msg.what = 1;
                msg.sendToTarget();
            }
        });
    }


    //按照日期排序
    private void SortData(List<MonthOrderInfo> infos) {
        Collections.sort(infos, new Comparator<MonthOrderInfo>() {
            @Override
            public int compare(MonthOrderInfo t, MonthOrderInfo t1) {
                String year = t.getMonth().substring(0, 4);
                String year1 = t.getMonth().substring(0, 4);
                String month = t.getMonth().substring(5, 7);
                String month1 = t.getMonth().substring(5, 7);
                LogUtil.e(year + "  " + month);
                if (Integer.valueOf(year) != Integer.valueOf(year1)) {
                    return year.compareTo(year1);
                } else {
                    return month.compareTo(month1);
                }
            }
        });
    }
}
